import hashlib
import time
import urllib.parse

class TengtuSignGenerator:
    def __init__(self):
        # API接口配置
        self.api_key = "k8f1z7k3u9x0vb4dlsn2h5qgemywtroc"
        self.app_id = "wxm9qz3k7trcylf2pa"
        self.channel_id = "47"
        
        # 跳转URL配置
        self.secret = "mZq8R1yVwH+Ln3aQb6T0uKfX2p9cJ4sA0vW8gYd3eF1oBmU5rNq2Lz7xCkPjS6hQyVtRbXcZp9UoK3mHfE4sTqW1nA8vY2cB5dG0eLjR7sPfQ6uMzNwXyVb8kHcJ2rL4tPzS9aF1oGqY6uD3mV0xC7sN5bH8pK2zR4wTjU1yQeLcO9vF6gM3hB0nS5pZ7rX2tV8wYcK4mN1qD6oF9uG3bP0zH5sJ2lR8eV7xT4yC1kM6nQ9aB3uD0vW5fG2hL8oPzR1sT6yN4cJ7qM9bA0eK3wV5uF2xH8rL6pS1tZ4yC9nD7mQ0gB3vH5oR2kF8wJ1sL6tP4zY9uV0cM3eN5qG7hB2rX8"
    
    def generate_api_sign(self, params):
        """
        生成API接口的sign（MD5）
        """
        # 按字段名排序并拼接
        sorted_params = sorted(params.items())
        param_str = "&".join([f"{k}={v}" for k, v in sorted_params])
        full_str = f"{param_str}&key={self.api_key}"
        print(f"拼接字符串: {full_str}")
        # 计算MD5
        md5 = hashlib.md5()
        md5.update(full_str.encode('utf-8'))
        return md5.hexdigest()
    
    def generate_url_sign(self, device_id, mac_address, timestamp):
        """
        生成跳转URL的sign（SHA256）
        """
        # 按顺序拼接所有字段（不要加任何分隔符）
        raw_str = f"{device_id}{mac_address}{self.channel_id}{timestamp}{self.secret}"
        
        # 计算SHA256
        sha256 = hashlib.sha256()
        sha256.update(raw_str.encode('utf-8'))
        return sha256.hexdigest()
    
    def verify_url_sign(self, device_id, mac_address, timestamp, client_sign):
        """
        验证跳转URL的签名
        """
        server_sign = self.generate_url_sign(device_id, mac_address, timestamp)
        return server_sign == client_sign
    
    def generate_redirect_url(self, device_id, mac_address, timestamp=None):
        """
        生成完整的跳转URL
        """
        if timestamp is None:
            timestamp = str(int(time.time() * 1000))  # 毫秒时间戳
            
        sign = self.generate_url_sign(device_id, mac_address, timestamp)
        
        base_url = "https://www.tt-wf.com/guide/index.html"
        params = {
            "src": "route",
            "macAddress": mac_address,
            "deviceId": device_id,
            "channelId": self.channel_id,
            "timestamp": timestamp,
            "sign": sign,
            "sign_ver": "1"
        }
        
        # 构建URL参数
        param_str = "&".join([f"{k}={v}" for k, v in params.items()])
        return f"{base_url}?{param_str}"

def display_header():
    print("=" * 70)
    print("                腾途签名生成工具")
    print("=" * 70)
    print()

def demo_api_signatures():
    print("1. API接口签名演示")
    print("-" * 50)
    
    sign_gen = TengtuSignGenerator()
    
    # 接口1示例
    params1 = {
        "app_id": sign_gen.app_id,
        "channelId": sign_gen.channel_id,
        "deviceId": "TEST01",
        "macAddress": "11:22:33:44:55:66"
    }
    
    sign1 = sign_gen.generate_api_sign(params1)
    print("接口1参数:")
    for k, v in params1.items():
        print(f"  {k}: {v}")
    print(f"接口1签名: {sign1}")
    print(f"预期签名: ad4d76d50958e2efa2b77468f72d14ca")
    print(f"验证结果: {'✓ 匹配成功' if sign1 == 'ad4d76d50958e2efa2b77468f72d14ca' else '✗ 匹配失败'}")
    print()
    
    # 接口2示例
    params2 = {
        "app_id": sign_gen.app_id,
        "channelId": sign_gen.channel_id,
        "deviceId": "TEST01"
    }
    
    sign2 = sign_gen.generate_api_sign(params2)
    print("接口2参数:")
    for k, v in params2.items():
        print(f"  {k}: {v}")
    print(f"接口2签名: {sign2}")
    print(f"预期签名: f1244f72a5c460609dd6361b8383780a")
    print(f"验证结果: {'✓ 匹配成功' if sign2 == 'f1244f72a5c460609dd6361b8383780a' else '✗ 匹配失败'}")
    print()

def demo_url_signature():
    print("2. 跳转URL签名演示")
    print("-" * 50)
    
    sign_gen = TengtuSignGenerator()
    
    device_id = "TEST01"
    mac_address = "b2:9d:ed:ca:d6:29"
    timestamp = "1740814304911"
    
    url_sign = sign_gen.generate_url_sign(device_id, mac_address, timestamp)
    print(f"设备ID: {device_id}")
    print(f"MAC地址: {mac_address}")
    print(f"渠道ID: {sign_gen.channel_id}")
    print(f"时间戳: {timestamp}")
    print(f"生成签名: {url_sign}")
    print(f"预期签名: 98119835ebe4f4b8f37314181a12116ee27d629e069ce3a59bb9212aff7543cb")
    print(f"验证结果: {'✓ 匹配成功' if url_sign == '98119835ebe4f4b8f37314181a12116ee27d629e069ce3a59bb9212aff7543cb' else '✗ 匹配失败'}")
    print()

def demo_redirect_url():
    print("3. 跳转URL生成演示")
    print("-" * 50)
    
    sign_gen = TengtuSignGenerator()
    
    device_id = "TEST123"
    mac_address = "aa:bb:cc:dd:ee:ff"
    
    redirect_url = sign_gen.generate_redirect_url(device_id, mac_address)
    print(f"设备ID: {device_id}")
    print(f"MAC地址: {mac_address}")
    print(f"生成的跳转URL:")
    print(redirect_url)
    print()

def demo_signature_verification():
    print("4. 签名验证演示")
    print("-" * 50)
    
    sign_gen = TengtuSignGenerator()
    
    # 使用文档中的示例数据进行验证
    is_valid = sign_gen.verify_url_sign(
        device_id="TEST01",
        mac_address="b2:9d:ed:ca:d6:29",
        timestamp="1740814304911",
        client_sign="98119835ebe4f4b8f37314181a12116ee27d629e069ce3a59bb9212aff7543cb"
    )
    
    print("验证数据:")
    print("  设备ID: TEST01")
    print("  MAC地址: b2:9d:ed:ca:d6:29")
    print("  时间戳: 1740814304911")
    print("  客户端签名: 98119835ebe4f4b8f37314181a12116ee27d629e069ce3a59bb9212aff7543cb")
    print(f"验证结果: {'✓ 签名有效' if is_valid else '✗ 签名无效'}")
    print()

def interactive_demo():
    print("5. 交互式演示")
    print("-" * 50)
    
    sign_gen = TengtuSignGenerator()
    
    print("生成跳转URL:")
    device_id = input("请输入设备ID (默认: TEST123): ") or "TEST123"
    mac_address = input("请输入MAC地址 (默认: aa:bb:cc:dd:ee:ff): ") or "aa:bb:cc:dd:ee:ff"
    
    use_custom_time = input("使用自定义时间戳? (y/N): ").lower() == 'y'
    if use_custom_time:
        timestamp = input("请输入时间戳 (毫秒): ")
    else:
        timestamp = None
    
    redirect_url = sign_gen.generate_redirect_url(device_id, mac_address, timestamp)
    print("\n生成的跳转URL:")
    print(redirect_url)
    print()

def main():
    display_header()
    
    # 演示API签名
    demo_api_signatures()
    
    # 演示URL签名
    demo_url_signature()
    
    # 演示跳转URL生成
    demo_redirect_url()
    
    # 演示签名验证
    demo_signature_verification()
    
    # 交互式演示
    interactive_demo()
    
    print("=" * 70)
    print("演示完成！")
    print("=" * 70)

if __name__ == "__main__":
    main()